package com.ctl.controller;

import com.ctl.dto.MsgDTO;
import com.ctl.sign.SignPrefig;
import com.ctl.util.SmsCodeUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class SmsContorller {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsCodeUtils smsCodeUtils;
    @PostMapping("/captchas")
    public void getCode(@RequestBody MsgDTO msg) throws Exception {
        //1. 获取手机号
        String phone = msg.getPhone();
        //2. 查看 redis是否存在该手机号
        if (redisTemplate.opsForValue().get(SignPrefig.PHONE_CODE+phone)!=null){
            throw new RuntimeException("已经发送过验证码，请60秒后再操作");
        }
        //3. 获取随机4位数作为验证码
        String code = RandomStringUtils.randomNumeric(4);
        smsCodeUtils.sendCode(phone,code);
        //4. 将手机存入redis数据库
        redisTemplate.opsForValue().set(SignPrefig.PHONE_CODE+phone,code,60, TimeUnit.SECONDS);
    }
}
